package com.steven.ourcontest.team.view

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.steven.ourcontest.R
import com.steven.ourcontest.app.AppRouter
import com.steven.ourcontest.base.BaseActivity
import com.steven.ourcontest.login.helper.LoginController
import com.steven.ourcontest.me.widget.GlideRoundTransform
import com.steven.ourcontest.net.NetConstants
import com.steven.ourcontest.team.adapter.TeamMemberAdapter
import com.steven.ourcontest.team.helper.TeamController
import com.steven.ourcontest.team.viewmodel.TeamViewModel
import com.steven.ourcontest.utils.DateUtil
import kotlinx.android.synthetic.main.activity_team_detail.*
import kotlinx.android.synthetic.main.activity_team_detail.tv_belong
import kotlinx.android.synthetic.main.activity_team_detail.tv_match_time
import kotlinx.android.synthetic.main.activity_team_detail.tv_rank
import kotlinx.android.synthetic.main.activity_team_detail.tv_signup_time
import kotlinx.android.synthetic.main.activity_team_detail.tv_url

class TeamDetailActivity : BaseActivity() {
    private val teamViewModel: TeamViewModel by viewModels()
    private var teamId: Long = 0
    private var isCollected: Boolean? = null
    private val adapter = TeamMemberAdapter(this) {
        if (it != LoginController.userId) {
            AppRouter.openUserDetailActivity(this, it)
        }
    }

    override fun getStatusBarColor(): Int {
        return R.color.white
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun getViewId(): Int? {
        return R.layout.activity_team_detail
    }

    @SuppressLint("SetTextI18n")
    override fun initView() {
        teamId = intent.getLongExtra("teamId", 0)
        if (teamId == 0L) {
            finish()
        }
        rv_member?.adapter = adapter
        teamViewModel.teamResponse.observe(this, Observer {
            val leaderId = it.teamAndLeader.belongUserId
            val isOpen = it.teamAndLeader.status == 1
            tv_team_name?.text = it.teamAndLeader.teamName
            tv_match?.text = "面向竞赛：${it.teamAndLeader.matchName}"
            val matchData = it.teamAndLeader
            matchData.belong?.let {
                tv_belong?.text = "主办方：${it}"
            }
            matchData.rank?.let {
                tv_rank?.text = "级别：${it}"
            }
            tv_signup_time?.text = "报名时间：${if (matchData.signUpStartTime != 0L && matchData.signUpEndTime != 0L) {
                DateUtil.timeStamp2Date(
                    matchData.signUpStartTime?.times(1000),
                    "yyyy.MM.dd"
                ) + "~" + DateUtil.timeStamp2Date(matchData.signUpEndTime?.times(1000), "yyyy.MM.dd")
            } else {
                "暂无"
            }}"
            tv_match_time?.text = "比赛时间：${if (matchData.matchStartTime != 0L && matchData.matchEndTime != 0L) {
                DateUtil.timeStamp2Date(
                    matchData.matchStartTime?.times(1000),
                    "yyyy.MM.dd"
                ) + "~" + DateUtil.timeStamp2Date(matchData.matchEndTime?.times(1000), "yyyy.MM.dd")
            } else {
                "暂无"
            }}"
            tv_url?.text = "参考网址：${matchData.url}"
            tv_url?.setOnClickListener {
                matchData.url?.let { it1 -> AppRouter.openWeb(this, it1) }
            }
            slide_view_status?.isChecked = isOpen
            TeamController.setTeamStatus(it.teamAndLeader.id, isOpen)
            Glide.with(this)
                .load(NetConstants.ICON_BASE_URL + it.teamAndLeader.leaderIconUrl)
                .error(R.drawable.ic_avatar)
                .apply(
                    RequestOptions.bitmapTransform(GlideRoundTransform(this, 10))
                ).into(iv_team_leader)
            tv_status?.text = "招募状态：${if (isOpen) {
                "开启"
            } else {
                "关闭"
            }}"
            tv_team_leader?.text =
                "${it.teamAndLeader.leaderName}${if (leaderId == LoginController.userId) {
                    "（自己）"
                } else {
                    ""
                }}"
            if (leaderId == LoginController.userId) {
                slide_view_status?.isVisible = true
                slide_view_status?.setOnCheckedChangeListener { buttonView, isChecked ->
                    teamViewModel.updateTeamStatus(teamId, isChecked) {
                        slide_view_status?.isChecked = TeamController.getTeamStatus(teamId)
                    }
                    tv_status?.text = "招募状态：${if (isChecked) {
                        "开启"
                    } else {
                        "关闭"
                    }}"
                }
            } else {
                slide_view_status?.isVisible = false
            }
            adapter.listData.clear()
            adapter.listData.addAll(it.member)
            adapter.notifyDataSetChanged()
            if (leaderId != LoginController.userId) {
                cl_leader?.setOnClickListener {
                    AppRouter.openUserDetailActivity(this, leaderId)
                }
                //判断是不是自己的队伍
                val res = it.member.filter { member ->
                    member.uid == LoginController.userId
                }
                if (res.isEmpty()) {
                    teamViewModel.addTeamPageViews(teamId)
                }
            }
            if (it.isCollected) {
                iv_collect?.setImageResource(R.drawable.ic_collected)
            } else {
                iv_collect?.setImageResource(R.drawable.ic_uncollected)
            }
            isCollected = it.isCollected
        })
        iv_collect?.setOnClickListener {
            if (isCollected == true) {
                teamViewModel.deleteTeamCollection(teamId) {
                    iv_collect?.setImageResource(R.drawable.ic_uncollected)
                    isCollected = false
                }
            } else if (isCollected == false) {
                teamViewModel.addTeamCollection(teamId) {
                    iv_collect?.setImageResource(R.drawable.ic_collected)
                    isCollected = true
                }
            }
        }
        teamViewModel.queryTeamDetail(teamId)
    }
}